from flask import Flask, jsonify, json, abort
from cassandra.cluster import Cluster  # 引入Cluster模块

app = Flask(__name__)

cluster = Cluster(['cassandra'])

session = cluster.connect()
# 创建 keyspace
session.execute("CREATE KEYSPACE if not exists todo WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3};")
# 指定 keyspace
session.execute('use todo;')
# 创建 table
session.execute('create table if not exists todo.todo(user_id int PRIMARY KEY,username text,event text);')


# session = cluster.connect('todo')  # 指定连接keyspace，相当于sql中use dbname

@app.route('/')
def hello():
    return 'hello flask'


# 插入todo
@app.route('/todos/<int:user_id>/<string:username>/<string:event>', methods=['POST'])
def create_todo(user_id, username, event):
    ls = [user_id, username, event]
    session.execute('insert into todo.todo (user_id,username, event) values (%s, %s, %s);', ls)
    return jsonify({'ID': user_id}), 201


# 删除todo
@app.route('/todos/<int:user_id>', methods=['DELETE'])
def delete_todo(user_id):
    ls = [user_id]
    session.execute('delete from todo.todo where user_id =%s;', ls)
    return jsonify({'result': True})


# 更新某条todo
@app.route('/todos/<string:event>/<int:user_id>', methods=['PUT'])
def update_todo(event, user_id):
    ls = [event, user_id]
    session.execute('update todo.todo set event = %s where user_id = %s', ls)
    return {'result': True}


# 列出所有的todo
@app.route('/todos', methods=['GET'])
def show_todos():
    rows = session.execute('select * from todo.todo')
    ls = []
    for i in rows:
        dict = {'id': i.user_id, 'username': i.username, 'event': i.event}
        ls.append(dict)
    return json.dumps(ls, ensure_ascii=False, indent=4), 200


if __name__ == '__main__':
    app.run()
